// 标签数据存储结构：{ [bookmarkId]: ["标签1", "标签2"] }
const TAGS_KEY = 'bookmark_tags';

// 获取所有标签数据
function getAllTags(callback) {
  chrome.storage.local.get([TAGS_KEY], (result) => {
    callback(result[TAGS_KEY] || {});
  });
}

// 保存标签数据
function saveAllTags(tagsObj, callback) {
  chrome.storage.local.set({ [TAGS_KEY]: tagsObj }, callback);
}

// 渲染书签树，支持标签过滤
function renderBookmarksTree(keyword = '', tagFilter = '') {
  chrome.bookmarks.getTree(function (bookmarkTreeNodes) {
    getAllTags((allTags) => {
      const treeContainer = document.getElementById('bookmark-tree');
      treeContainer.innerHTML = '';
      const lowerKeyword = keyword.trim().toLowerCase();
      const lowerTag = tagFilter.trim().toLowerCase();
      bookmarkTreeNodes.forEach(node => {
        const el = renderNode(node, lowerKeyword, lowerTag, allTags);
        if (el) treeContainer.appendChild(el);
      });
    });
  });
}

// 递归渲染节点，支持标题和标签过滤
function renderNode(node, keyword, tagFilter, allTags) {
  if (node.children && node.children.length > 0) {
    const filteredChildren = node.children
      .map(child => renderNode(child, keyword, tagFilter, allTags))
      .filter(el => el);
    if (filteredChildren.length > 0) {
      const folder = document.createElement('div');
      folder.className = 'bookmark-folder';
      folder.textContent = node.title || '未命名文件夹';
      filteredChildren.forEach(childEl => folder.appendChild(childEl));
      return folder;
    }
    return null;
  } else if (node.url) {
    const tags = allTags[node.id] || [];
    const matchTitle = !keyword || (node.title && node.title.toLowerCase().includes(keyword));
    const matchTag = !tagFilter || tags.some(t => t.toLowerCase().includes(tagFilter));
    if (matchTitle && matchTag) {
      const item = document.createElement('div');
      item.className = 'bookmark-item';
      const title = document.createElement('span');
      title.className = 'bookmark-title';
      title.textContent = node.title || node.url;
      title.title = node.url;
      title.onclick = () => {
        chrome.tabs.create({ url: node.url });
      };
      item.appendChild(title);
      // 标签显示
      const tagSpan = document.createElement('span');
      tagSpan.className = 'bookmark-tags';
      tagSpan.innerHTML = tags.map(t => `<span class="tag">${t}</span>`).join(' ');
      item.appendChild(tagSpan);
      // 编辑标签按钮
      const editBtn = document.createElement('button');
      editBtn.textContent = '标签';
      editBtn.className = 'edit-tag-btn';
      editBtn.onclick = (e) => {
        e.stopPropagation();
        showTagEditor(node.id, tags, allTags);
      };
      item.appendChild(editBtn);
      return item;
    }
    return null;
  } else {
    return null;
  }
}

// 标签编辑弹窗
function showTagEditor(bookmarkId, tags, allTags) {
  let input = prompt('请输入标签，多个标签用逗号分隔：', tags.join(','));
  if (input !== null) {
    const newTags = input.split(',').map(t => t.trim()).filter(Boolean);
    allTags[bookmarkId] = newTags;
    saveAllTags(allTags, () => {
      renderBookmarksTree(
        document.getElementById('search').value,
        document.getElementById('tag-filter') ? document.getElementById('tag-filter').value : ''
      );
    });
  }
}

// 渲染标签筛选栏
function renderTagFilterBar() {
  getAllTags((allTags) => {
    const allTagSet = new Set();
    Object.values(allTags).forEach(tagsArr => tagsArr.forEach(t => allTagSet.add(t)));
    const tagBar = document.getElementById('tag-filter-bar');
    tagBar.innerHTML = '';
    const input = document.createElement('input');
    input.type = 'text';
    input.id = 'tag-filter';
    input.placeholder = '标签筛选...';
    input.style.marginRight = '8px';
    input.addEventListener('input', function () {
      renderBookmarksTree(
        document.getElementById('search').value,
        this.value
      );
    });
    tagBar.appendChild(input);
    // 标签云
    allTagSet.forEach(tag => {
      const tagBtn = document.createElement('span');
      tagBtn.className = 'tag tag-btn';
      tagBtn.textContent = tag;
      tagBtn.onclick = () => {
        input.value = tag;
        input.dispatchEvent(new Event('input'));
      };
      tagBar.appendChild(tagBtn);
    });
  });
}

document.addEventListener('DOMContentLoaded', function () {
  renderBookmarksTree();
  renderTagFilterBar();
  const searchInput = document.getElementById('search');
  searchInput.addEventListener('input', function () {
    renderBookmarksTree(this.value, document.getElementById('tag-filter') ? document.getElementById('tag-filter').value : '');
  });
}); 